import { readFileSync, writeFileSync, mkdirSync } from 'fs'
import { join } from 'path'
import siteConfig from '../site.config.js'

/**
 * Vite 插件：根据路由配置自动生成 sitemap.xml
 */
export function sitemapReplacer() {
  return {
    name: 'sitemap-generator',
    closeBundle() {
      const config = siteConfig
      const domain = config.domain || 'your-domain.com'
      const protocol = config.useHttps !== false ? 'https' : 'http'
      const baseUrl = `${protocol}://${domain}`
      
      try {
        // 读取路由配置
        const routesConfigPath = join(process.cwd(), 'src', 'router', 'index.js')
        const routesContent = readFileSync(routesConfigPath, 'utf-8')
        
        // 解析路由配置
        const routes = extractRoutes(routesContent)
        
        // 生成 sitemap.xml
        const sitemapXml = generateSitemap(routes, baseUrl, config)
        
        // 确保目录存在
        const sitemapDir = join(process.cwd(), 'dist', 'sitemap')
        mkdirSync(sitemapDir, { recursive: true })
        
        // 写入生成的 sitemap.xml
        const sitemapPath = join(sitemapDir, 'sitemap.xml')
        writeFileSync(sitemapPath, sitemapXml, 'utf-8')
        console.log(`✓ Sitemap generated: ${routes.length} URLs, ${baseUrl}`)
        
        // 更新 robots.txt
        updateRobotsTxt(baseUrl)
        console.log(`✓ Robots.txt updated: ${baseUrl}`)
      } catch (error) {
        console.error('❌ Error generating sitemap:', error.message)
        console.error(error.stack)
      }
    }
  }
}

/**
 * 从路由配置文件中提取路由信息
 */
function extractRoutes(routesContent) {
  const routes = []
  
  // 匹配路由对象：path、name、meta
  // 使用更宽松的正则来匹配多行路由定义
  const routeRegex = /path:\s*['"]([^'"]+)['"][\s\S]*?name:\s*['"]([^'"]+)['"][\s\S]*?(?:meta:\s*\{([\s\S]*?)\})?/g
  
  let match
  while ((match = routeRegex.exec(routesContent)) !== null) {
    const path = match[1]
    const name = match[2]
    const metaBlock = match[3] || ''
    
    // 提取 meta 信息
    const titleMatch = metaBlock.match(/title:\s*['"]([^'"]+)['"]/)
    const keywordsMatch = metaBlock.match(/keywords:\s*['"]([^'"]+)['"]/)
    const descriptionMatch = metaBlock.match(/description:\s*['"]([^'"]+)['"]/)
    
    routes.push({
      path,
      name,
      title: titleMatch ? titleMatch[1] : name,
      keywords: keywordsMatch ? keywordsMatch[1] : '',
      description: descriptionMatch ? descriptionMatch[1] : ''
    })
  }
  
  return routes
}

/**
 * 生成 sitemap.xml 内容
 */
function generateSitemap(routes, baseUrl, config) {
  const today = new Date().toISOString().split('T')[0]
  
  let xml = '<?xml version="1.0" encoding="UTF-8"?>\n'
  xml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
  
  routes.forEach((route, index) => {
    // 首页优先级最高，前几个工具页面次之
    const priority = route.path === '/' ? '1.0' : (index <= 2 ? '0.9' : '0.8')
    const changefreq = route.path === '/' ? 'weekly' : 'monthly'
    const lastmod = config.autoUpdateLastmod !== false ? today : '2024-12-19'
    
    xml += '  <url>\n'
    xml += `    <loc>${baseUrl}${route.path}</loc>\n`
    xml += `    <lastmod>${lastmod}</lastmod>\n`
    xml += `    <changefreq>${changefreq}</changefreq>\n`
    xml += `    <priority>${priority}</priority>\n`
    xml += '  </url>\n'
  })
  
  xml += '</urlset>\n'
  return xml
}

/**
 * 更新 robots.txt
 */
function updateRobotsTxt(baseUrl) {
  const robotsPath = join(process.cwd(), 'dist', 'robots.txt')
  try {
    const robotsContent = `User-agent: *
Allow: /

# Sitemap位置
Sitemap: ${baseUrl}/sitemap/sitemap.xml
`
    writeFileSync(robotsPath, robotsContent, 'utf-8')
  } catch (error) {
    console.warn('⚠ Warning: Could not update robots.txt:', error.message)
  }
}
